package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import io.netty.util.internal.ResourcesUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;
    /**
     * 下载
     * @param name
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/download",produces = MediaType.IMAGE_JPEG_VALUE)
    public void downloadImage(String name, HttpServletResponse response) throws IOException {
//        String property = System.getProperty("user.dir");
//        File file =new File(property+basePath+name);
//        System.out.println(file.getAbsolutePath());
        InputStream inputStream = new ClassPathResource("\\images\\" + name).getInputStream();

        try (
                ServletOutputStream outputStream = response.getOutputStream()) {
          int read;
          byte[] bytes = new byte[1024];
          while ((read=inputStream.read(bytes))!=-1){
              outputStream.write(bytes,0,read);
              outputStream.flush();
          }
        }
    }

    @PostMapping("/upload")
    public R<String> uploadImage(MultipartFile file) {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //切割后缀名并使用UUID生成新的文件名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString()+suffix;
        System.out.println(filename);

        //创建存放图片的目录对象
        File imageDirectory = new File(basePath);
        if (!imageDirectory.exists()){
            //目录不存在，创建新目录
            imageDirectory.mkdirs();
        }
        try {
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回文件名给前端用于生成预览图
        return R.success(filename);
    }
}
